import React from 'react';
import {connect} from 'react-redux';
import menuRoute from 'routes/menuRoute';
import SearchArea from 'components/search-area';
import {messages} from "share/common";
import AuthSearcherService from 'containers/permission-setting/auth-searcher/auth-searcher.service';
import 'styles/permission-setting/auth-searcher/auth-searcher.scss';
import ResizeTable from 'components/resize-table'
import antdc from 'share/prototype-extend/antd-common';
import RSService from 'containers/permission-setting/components/role-menu.service';
import {permissionTypeList,} from 'containers/permission-setting/permission-setting.model';

class AuthSearcher extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      detailUrl: menuRoute.getRouteItem('role-permission-setting-detail', 'key').url,
      loading: true,
      data: [],
      params: {},
      searchParams: {
        companyId: "",
        departmentId: "",
        userId: "",
        permissionCategory: "",//职能类型 （传编码 FINANCE , ADMIN ,OTHER）
        permissionId: "",//职能名称对应的职能Id   （职能列表的用进入授权管理的 租户下职能类表）
      },
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      searchForm: [
        {
          type: 'list',
          id: 'companyId',
          label: messages('permission-setting.key66')/*公司*/,
          listType: 'all_company_with_legal_entity',
          labelKey: 'companyName',
          valueKey: 'id',
          placeholder: messages('common.select')/*请选择*/,
          single: true,
        },
        {
          type: 'list',
          id: 'departmentId',
          label: messages('common.department')/*部门*/,
          listType: 'department',
          labelKey: 'name',
          valueKey: 'departmentId',
          placeholder: messages('common.select')/*请选择*/,
          single: true,
        },
        {
          type: 'list',
          id: 'userId',
          label: messages('permission-setting.key92')/*员工*/,
          listType: 'user',
          labelKey: 'fullName',
          valueKey: 'id',
          placeholder: messages('common.select')/*请选择*/,
          single: true,
        },
        {
          type: 'select',
          id: 'permissionCategory',
          label: messages('permission-setting.key93')/*职能类型*/,
          options: permissionTypeList,
        },
        {
          type: 'select',
          id: 'permissionId',
          label: messages('permission-setting.key7')/*职能名称*/,
          options: []
        },
      ],
      columns: [
        {
          title: messages('permission-setting.key92')/*员工*/,
          key: "userName",
          dataIndex: 'userName',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('common.department')/*部门*/,
          key: "departmentName",
          dataIndex: 'departmentName',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('permission-setting.key66')/*公司*/,
          key: "companyName",
          dataIndex: 'companyName',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('permission-setting.key5')/*职能类别*/,
          key: "permissionCategory",
          dataIndex: 'permissionCategory',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('permission-setting.key7')/*职能名称*/,
          key: "permissionName",
          dataIndex: 'permissionName',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('permission-setting.key41')/*授权策略描述*/,
          key: "authName",
          dataIndex: 'authName',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('permission-setting.key36')/*组织权限*/,
          key: "_permissionProp",
          dataIndex: '_permissionProp',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages("common.operation"), //操作
          dataIndex: 'userId',
          width: '10%',
          key: "id",
          render: (text, record) => (
            <span>
              <a style={{marginRight: 10}} onClick={(e) => this.handleRowClick(e, record)}>
                {/*详情*/}
                {messages("common.detail")}
              </a>
            </span>
          )
        }
      ],
    };
  }

  componentDidMount() {
    this.getList();
    //记住页码
    // let _pagination = this.getBeforePage("authSearcher");
    // let pagination = this.state.pagination;
    // pagination.page = _pagination.page;
    // pagination.current = _pagination.page + 1;
    // this.setState({
    //   pagination,
    // }, () => {
    //   this.clearBeforePage("authSearcher");
    //   this.getList();
    // })
    this.getRoleList();
  }

  //获取角色列表
  getRoleList = () => {
    this.setState({
      loading: true
    });
    let {searchForm} = this.state;
    RSService.getRoleList()
      .then(res => {
        let permissonList = res.data.map(item => {
          let _item = {
            value: item.id,
            label: item.permissionName
          };
          return _item
        });
        searchForm[4].options = permissonList;
        this.setState({
          searchForm
        })
      })
  };


  getList() {
    this.setState({loading: true});
    let pagination = this.state.pagination;
    let params = this.state.searchParams;
    params.page = pagination.page;
    params.size = pagination.pageSize;
    AuthSearcherService.getAuthorizationUserList(params)
      .then((response) => {
        pagination.total = Number(response.headers['x-total-count']);
        let mapName = {
          "ALL": messages('permission-setting.key32')/*全租户*/,
          "OTHER": messages('permission-setting.key33')/*部分*/,
          "COMPANY": messages('permission-setting.key34')/*人员所在公司*/
        }
        response.data.map(item => {
          item._permissionProp = mapName[item.permissionProp]
        })
        this.setState({
          loading: false,
          data: response.data,
          pagination
        })
      })
  }

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    let temp = this.state.pagination;
    temp.page = pagination.current - 1;
    temp.current = pagination.current;
    temp.pageSize = pagination.pageSize;
    this.setState({
      loading: true,
      pagination: temp
    }, () => {
      this.getList();
    })
  };

  //点击搜搜索
  handleSearch = (params) => {
    let pagination = this.state.pagination;
    pagination.page = 0;
    pagination.current = 1;
    this.setState({
      pagination,
      searchParams: params
    }, () => {
      this.getList();
    });
  };
  //点击清除
  clearHandle = () => {
    this.setState({
      searchParams: {
        companyId: "",
        departmentId: "",
        userId: "",
        permissionCategory: "",//职能类型 （传编码 FINANCE , ADMIN ,OTHER）
        permissionId: "",//职能名称对应的职能Id   （职能列表的用进入授权管理的 租户下职能类表）
      }
    }, () => {
      this.getList();
    });
  }

  //跳转到详情
  handleRowClick = (e, record) => {
    // this.setBeforePage(this.state.pagination, "authSearcher");
    this.context.router.push({
      pathname: this.state.detailUrl.replace(':permissionId', record.authorizationPolicyId),
      state: {
        cRole: {},
      },
    });
  };

  render() {
    const {loading, searchForm, data, pagination, columns} = this.state;
    return (
      <div className="auth-searcher">
        <SearchArea searchForm={searchForm}
                    clearHandle={this.clearHandle}
                    submitHandle={this.handleSearch}/>
        <div className="table-header">
          <div
            className="table-header-title">
            {messages('common.total', {total: `${pagination.total}`})}
          </div>
          {/*共搜索到*条数据*/}
        </div>
        <ResizeTable
          loading={loading}
          dataSource={data}
          columns={columns}
          pagination={pagination}
          size="middle"
          bordered
          onChange={this.onChangePager}
        />
      </div>
    )
  }

}

AuthSearcher.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.login.organization,
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
  }
}

export default connect(mapStateToProps)(AuthSearcher);
